package ssi.actions;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionRedirect;

import ssi.beans.User;
import ssi.tools.Connector;

public class AdToFavouritesAction extends Action {
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		request.setCharacterEncoding("UTF-8");
		HttpSession session = request.getSession(true);
		String target=null;
		User user=(User)form;
		User users = (User)session.getAttribute("user");
		String userID = String.valueOf(users.getId());
		String animalID = user.getAnimalID();
		String query = "SELECT COUNT(*) FROM `favourites` WHERE `animalId`="+animalID+" AND `userId`="+userID;
		try{
			Connection connection = new Connector().getConnection();
    		Statement statement = connection.createStatement();
    		ResultSet rs = statement.executeQuery(query);
    		rs.next();
    		if(rs.getInt("COUNT(*)")==0){
    			query = "INSERT INTO `favourites`(`userId`, `animalId`) VALUES("+userID+","+animalID+")";
    			statement.executeUpdate(query);
    			target="success";
    			connection.close();
    		} else{
    			target="failure";
    		}
		} catch(Exception e){
			e.printStackTrace();
		}
		ActionRedirect redirect = new ActionRedirect(mapping.findForward(target));
		redirect.addParameter("id", animalID);
		return redirect;
	}

}
